package com.example.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.constant.Code;
import com.example.dto.LoginDto;
import com.example.dto.UserDto;
import com.example.service.UserService;
import com.example.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author itheima
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;

    @ApiOperation("获取验证码")
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        if (ObjectUtil.isEmpty(loginDto)) {
            return Result.error("用户信息不能为空" + Code.FORBIDDEN);
        }
        Boolean flag = userService.sendMsg(loginDto);
        if (flag) {
            return Result.success("发送成功");
        }
        return Result.error("发送失败");
    }

    @ApiOperation("检验登录")
    @PostMapping("/loginVerification")
    public Result loginVerification(@RequestBody LoginDto loginDto) {
        if (ObjectUtil.isEmpty(loginDto)) {
            return Result.error("用户信息不能为空" + Code.FORBIDDEN);
        }
        LoginVo loginVo = userService.login(loginDto);
        return Result.success(loginVo);
    }

    @ApiOperation("修改用户信息")
    @PutMapping("/loginReginfo")
    public Result updateUser(@RequestBody UserDto userDto) {
        if (ObjectUtil.isEmpty(userDto)) {
            return Result.error("用户信息不能为空" + Code.FORBIDDEN);
        }
        Boolean flag = userService.updateUser(userDto);
        if (flag) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    @PostMapping("/checkCode")
    public Result checkCode(@RequestBody LoginDto loginDto) {
        if (ObjectUtil.isEmpty(loginDto)) {
            return Result.error("用户信息不能为空" + Code.FORBIDDEN);
        }
        Boolean flag = userService.checkCode(loginDto);
        if (flag) {
            return Result.success("验证码校验成功");
        }
        return Result.error("验证码失败");
    }

    @PostMapping("/updatePhone")
    public Result updatePhone(@RequestBody LoginDto loginDto) {
        if (ObjectUtil.isEmpty(loginDto)) {
            return Result.error("用户信息不能为空" + Code.FORBIDDEN);
        }
        Boolean flag = userService.updatePhone(loginDto);
        if (flag == null) {
            return Result.error("验证码错误/该手机号已被绑定，请重新输入新手机号");
        }
        if (flag) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

}
